package com.cy.interfacetest.activity;

import android.Manifest;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;

import com.cy.interfacetest.R;
import com.cy.interfacetest.policyinterface.IPolicyManager;
import com.cy.interfacetest.policyinterface.impl.IPolicyManagerImpl;
import com.cy.interfacetest.proxy.ModuleProxy;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import ga.mdm.PolicyManager;

@RequiresApi(api = Build.VERSION_CODES.N)
public class MainActivity extends BaseActivity {
    private static final String TAG = "MainActivity";
    private static final int REQUEST_CODE_STORAGE_PERMISSION = 1;
    private static final int REQUEST_INSTALL_PACKAGES = 2;
    private static IPolicyManager pm = new ModuleProxy<IPolicyManager>().getInstance(new IPolicyManagerImpl(PolicyManager.getInstance()));

    //todo 出厂设置和调试模式 不能同时开启的标签
    private static final Map<String, Integer> flag = new HashMap<>();


    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("限制策略");

      /*  PolicyManager instance = PolicyManager.getInstance();
        instance.setWlanPolicies(2);*/
        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_STORAGE_PERMISSION);
    }


    public void notAllowWlan(View view) {
        try {
            switchPassOrFailure(pm.setWlanPolicies(0), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void scanWlan(View view) {
        try {
            switchPassOrFailure(pm.setWlanPolicies(1), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }


    public void allowWlan(View view) {
        try {
            switchPassOrFailure(pm.setWlanPolicies(isZETDevice() ? 3 : 2), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void notAllowDataConnectivity(View view) {
        try {
            switchPassOrFailure(pm.setDataConnectivityPolicies(0), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void AllowDataConnectivity(View view) {
        try {
            switchPassOrFailure(pm.setDataConnectivityPolicies(2), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void DataConnectivityOn(View view) {
        try {
            switchPassOrFailure(pm.setDataConnectivityPolicies(1), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }


    public void notAllowtBluetooth(View view) {
        try {
            switchPassOrFailure(pm.setBluetoothPolicies(0, new String[]{}), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void AllowPartBluetooth(View view) {
        TextView textView = (TextView) findViewById(R.id.bluetooth_mac);
        String text = textView.getText().toString().trim();
        if (text.length() <= 15 || !text.contains(":")) {
            Toast.makeText(this, "请输入正确mac", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            switchPassOrFailure(pm.setBluetoothPolicies(1, new String[]{"{\"Mac\":\"" + text + "\"}"}), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void notAllowNFC(View view) {
        try {
            switchPassOrFailure(pm.setNfcPolicies(0), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }

    }

    public void forceOpenNfc(View view) {
        try {
            switchPassOrFailure(pm.setNfcPolicies(1), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void allowOpenNfc(View view) {
        try {
            switchPassOrFailure(pm.setNfcPolicies(2), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void notAllowInfrared(View view) {
        try {
            switchPassOrFailure(pm.setIrPolicies(0), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void allowInfrared(View view) {
        try {
            switchPassOrFailure(pm.setIrPolicies(1), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void notAllowBiometrics(View view) {
        try {
            switchPassOrFailure(pm.setBiometricRecognitionPolicies(0), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void allBiometrics(View view) {
        try {
            switchPassOrFailure(pm.setBiometricRecognitionPolicies(1), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }


    public void notAllowGPS(View view) {
        try {
            switchPassOrFailure(pm.setGpsPolicies(0), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void forceOpenGPS(View view) {
        try {
            switchPassOrFailure(pm.setGpsPolicies(1), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void allowGPS(View view) {
        try {
            switchPassOrFailure(pm.setGpsPolicies(2), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void notAllowUsbData(View view) {
        try {
            switchPassOrFailure(pm.setUsbDataPolicies(0), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void allowUsbData(View view) {
        try {
            switchPassOrFailure(pm.setUsbDataPolicies(1), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void notAllowRW(View view) {
        try {
            switchPassOrFailure(pm.setExternalStoragePolicies(0), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void AllowR(View view) {
        try {
            switchPassOrFailure(pm.setExternalStoragePolicies(1), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void allowRD(View view) {
        try {
            switchPassOrFailure(pm.setExternalStoragePolicies(2), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void notAllowMicrophone(View view) {
        try {
            switchPassOrFailure(pm.setMicrophonePolicies(0), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void allowMicrophone(View view) {
        try {
            switchPassOrFailure(pm.setMicrophonePolicies(1), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void notAllowSpeaker(View view) {
        try {
            switchPassOrFailure(pm.setSpeakerPolicies(0), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void AllowSpeaker(View view) {
        try {
            switchPassOrFailure(pm.setSpeakerPolicies(1), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void notAllowCamera(View view) {
        try {
            switchPassOrFailure(pm.setCameraPolicies(0), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void AllowCamera(View view) {
        try {
            switchPassOrFailure(pm.setCameraPolicies(1), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }


    public void notAllowFlash(View view) {
        try {
            switchPassOrFailure(pm.setFlashPolicies(0), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void allowFlash(View view) {
        try {
            switchPassOrFailure(pm.setFlashPolicies(1), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void notAllowPeripherals(View view) {
        try {
            switchPassOrFailure(pm.setPeripheralPolicies(0), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void AllowPeripherals(View view) {
        try {
            switchPassOrFailure(pm.setPeripheralPolicies(1), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    // TODO: 2023/8/9  终端基本功能管控接口

    public void notAllowVoice(View view) {
        try {
            switchPassOrFailure(pm.setVoicePolicies(0), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void allowVoice(View view) {
        try {
            switchPassOrFailure(pm.setVoicePolicies(1), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void notAllowtSms(View view) {
        try {
            switchPassOrFailure(pm.setSmsPolicies(0, null), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void allowSms(View view) {
        try {
            switchPassOrFailure(pm.setSmsPolicies(1, null), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void notAllowCaptureScreen(View view) {
        try {
            switchPassOrFailure(pm.setCaptureScreenPolicies(0), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void AllowCaptureScreen(View view) {
        try {
            switchPassOrFailure(pm.setCaptureScreenPolicies(1), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void notAllowWlanAp(View view) {
        try {
            switchPassOrFailure(pm.setWlanApPolicies(0, new String[]{}), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void AllowPartWlanAp(View view) {
        try {
            EditText editt = (EditText) findViewById(R.id.wlan_mac);
            if (editt.toString().length() <= 15) {
                Toast.makeText(this, "请输入mac地址", Toast.LENGTH_SHORT).show();
            } else {
                switchPassOrFailure(pm.setWlanApPolicies(1, new String[]{editt.getText().toString().trim()}), view);
            }
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void notAllowApnMgr(View view) {
        try {
            switchPassOrFailure(pm.setUserApnMgrPolicies(0), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void AllowApnMgrView(View view) {
        try {
            switchPassOrFailure(pm.setUserApnMgrPolicies(1), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void AllowApnMgr(View view) {
        try {
            switchPassOrFailure(pm.setUserApnMgrPolicies(2), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }


    public void Passwordmode0(View view) {
        try {
            switchPassOrFailure(pm.setUserPasswordPolicies(0), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void Passwordmode1(View view) {
        try {
            switchPassOrFailure(pm.setUserPasswordPolicies(1), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void Passwordmode2(View view) {
        try {
            switchPassOrFailure(pm.setUserPasswordPolicies(2), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void Passwordmode3(View view) {
        try {
            switchPassOrFailure(pm.setUserPasswordPolicies(3), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void forceOpenTimeMgr(View view) {
        try {
            switchPassOrFailure(pm.setUserTimeMgrPolicies(0), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void allowTimeMgr(View view) {
        try {
            switchPassOrFailure(pm.setUserTimeMgrPolicies(1), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    Handler handler = new Handler();

    public void notAllowReset(View view) {
        String k = "Reset";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Integer integer = flag.entrySet().stream().map(Map.Entry::getValue).reduce(Integer::sum).orElse(0);
            if (integer < 1) {
                try {
                    switchPassOrFailure(pm.setFactoryResetPolicies(0), view);
                    flag.put(k, 1);
                } catch (Exception e1) {
                    switchPassOrFailure(false, view);
                    e1.printStackTrace();
                }
            } else {
                handler.post(() -> {
                    Toast.makeText(MainActivity.this, "恢复出厂和开发者不能同时禁用", Toast.LENGTH_SHORT).show();
                });
            }
        } else {
            handler.post(() -> {
                Toast.makeText(MainActivity.this, "版本低", Toast.LENGTH_SHORT).show();
            });
        }

    }


    public void allowReset(View view) {
        try {
            switchPassOrFailure(pm.setFactoryResetPolicies(1), view);
            String k = "Reset";
            flag.put(k, 0);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void notAllowDevelop(View view) {
        String k = "Develop";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Integer integer = flag.entrySet().stream().map(Map.Entry::getValue).reduce(Integer::sum).orElse(0);
            if (integer < 1) {
                try {
                    switchPassOrFailure(pm.setDevelopmentModePolicies(0), view);
                    flag.put(k, 1);
                } catch (Exception e) {
                    switchPassOrFailure(false, view);
                    e.printStackTrace();
                }
            } else {
                handler.post(() -> {
                    Toast.makeText(MainActivity.this, "恢复出厂和开发者不能同时禁用", Toast.LENGTH_SHORT).show();
                });
            }
        } else {
            handler.post(() -> {
                Toast.makeText(MainActivity.this, "版本低", Toast.LENGTH_SHORT).show();
            });
        }
    }

    public void allowDevelop(View view) {
        String k = "Develop";
        try {
            switchPassOrFailure(pm.setDevelopmentModePolicies(1), view);
            flag.put(k, 0);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void notAllowSystemUpdate(View view) {
        try {
            switchPassOrFailure(pm.setSystemUpdatePolicies(0), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void allowSystemUpdate(View view) {
        try {
            switchPassOrFailure(pm.setSystemUpdatePolicies(1), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void notAllowAdbInstallOrUn(View view) {
        try {
            switchPassOrFailure(pm.setAdbInstallUninstallPolicies(1), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void allowAdbInstallOrUn(View view) {
        try {
            switchPassOrFailure(pm.setAdbInstallUninstallPolicies(0), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void notAllowInstallOrUn(View view) {
        try {
            switchPassOrFailure(pm.setInstallUninstallPolicies(0, null), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void AllowPartInstallOrUn(View view) {
        String s = "{\"AppPackageName\":\"com.cy.interfacetest\",\"CertificateHash\":\"65D0D48C301E5B54F40D880D39AB9C7104C671AC\"}";
        String S1 = "{\"AppPackageName\":\"com.nq.mdm\",\"CertificateHash\":\"65D0D48C301E5B54F40D880D39AB9C7104C671AC\"}";
        try {
            switchPassOrFailure(pm.setInstallUninstallPolicies(1, new String[]{s, S1}), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void installApp(View view) {
        Log.i(TAG, "installApp: ");
        // 获取 AssetManager 实例
        String filePath = getFilePath();
        install(new File(filePath));
    }


    public String getFilePath() {
        // 获取 AssetManager 实例
        AssetManager assetManager = getAssets();
        String path = null;
        try (InputStream inputStream = assetManager.open("openWifi.apk")) { // 打开名为 "sample.txt" 的文件
            // 读取文件内容
            path = Environment.getExternalStorageDirectory() + File.separator + "openWifi.apk";
            createFileFromStream(inputStream, new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }

    public void createFileFromStream(InputStream ins, File destination) {
        try (OutputStream os = new FileOutputStream(destination)) {
            byte[] buffer = new byte[4096];
            int length;
            while ((length = ins.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
            os.flush();
        } catch (Exception ex) {
            Log.e("Save File", ex.getMessage());
            ex.printStackTrace();
        }
    }

    public void install(File filePath) {
        Log.i(TAG, "install: Path = " + filePath.getAbsolutePath());
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri;
        if (Build.VERSION.SDK_INT >= 24) {//android 7.0以上
            uri = FileProvider.getUriForFile(this, "com.cy.interfacetest.fileprovider", filePath);
        } else {
            uri = Uri.fromFile(filePath);
        }
        Log.i(TAG, "install: uri = " + uri.toString());
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 24) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        startActivity(intent);
    }

    public void unInstall(View view) {
        Uri uri = Uri.fromParts("package", "com.nq.police.setting.wifi", null);
        Intent intent = new Intent(Intent.ACTION_DELETE, uri);
        startActivity(intent);
    }


    public void AllowInstallOrUn(View view) {
        try {
            switchPassOrFailure(pm.setInstallUninstallPolicies(2, null), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }


    public void notAllowSilentInstallOrUn(View view) {
        try {
            switchPassOrFailure(pm.setSilentInstallUninstallPolicies(0, null), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void allowSilentInstallOrUn(View view) {
        try {
            switchPassOrFailure(pm.setSilentInstallUninstallPolicies(2, null), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void AllowPartSilentInstallOrUn(View view) {
        String s = "{\"AppPackageName\":\"com.cy.interfacetest\",\"CertificateHash\":\"65D0D48C301E5B54F40D880D39AB9C7104C671AC\"}";
        String s1 = "{\"AppPackageName\":\"com.nq.mdm\",\"CertificateHash\":\"65D0D48C301E5B54F40D880D39AB9C7104C671AC\"}";

        try {
            switchPassOrFailure(pm.setSilentInstallUninstallPolicies(1, new String[]{s, s1}), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void SilentInstallApp(View view) {
        try {
            switchPassOrFailure(pm.installPackage(getFilePath()), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }

    public void SilentUnInstallApp(View view) {
        try {
            switchPassOrFailure(pm.uninstallPackage("com.nq.police.setting.wifi"), view);
        } catch (Exception e) {
            switchPassOrFailure(false, view);
            e.printStackTrace();
        }
    }
}


